package br.jcrsistemas.componentes;

import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Hashtable;

import javax.swing.JTabbedPane;
import javax.swing.KeyStroke;
import javax.swing.plaf.basic.BasicGraphicsUtils;
import javax.swing.plaf.basic.BasicTabbedPaneUI;


public class SysTabbedPane extends JTabbedPane {

	int indiceAtual = 0;
	Hashtable mnemonics = null;
	int condicao;

	public SysTabbedPane() {
		setTabPlacement(TOP);
		setUI(new SisComTabbedPaneUI());
		mnemonics = new Hashtable();
		condicao = WHEN_IN_FOCUSED_WINDOW;
	}
	
	
	public void setMnemonic(char c) {
		int key = (int) c;
		if ('a' <= key && key <= 'z') {
			key -= ('a' - 'A');
		}
		setMnemonicAt(indiceAtual++, key);
	}
	
	public void setMnemonicAt(int index, char c) {
		int key = (int) c;
		if ('a' <= key && key <= 'z') {
			key -= ('a' - 'A');
		}
		setMnemonicAt(index, key);
	}
	public int getMnemonicAt(int index) {
		    int keyCode = 0;
		    Integer m = (Integer) mnemonics.get(new Integer(index));
		    if (m != null) {
		      keyCode = m.intValue();
		    }
		    return keyCode;
		  }


	public void setMnemonicAt(int index, int keyCode) {
		ActionListener action = new MnemonicAction(index);
		KeyStroke stroke = KeyStroke
				.getKeyStroke(keyCode, ActionEvent.ALT_MASK);
		registerKeyboardAction(action, stroke, condicao);
		mnemonics.put(new Integer(index), new Integer(keyCode));
	}

	class MnemonicAction implements ActionListener {
		int index;

		public MnemonicAction(int index) {
			this.index = index;
		}

		public void actionPerformed(ActionEvent e) {
			SysTabbedPane tabbedPane = (SysTabbedPane) e.getSource();
			tabbedPane.setSelectedIndex(index);
			tabbedPane.requestFocus();
		}
	}

	class SisComTabbedPaneUI extends BasicTabbedPaneUI {
		protected void paintText(Graphics g, int tabPlacement, Font font,
				FontMetrics metrics, int tabIndex, String title,
				Rectangle textRect, boolean isSelected) {
			g.setFont(font);
			SysTabbedPane mtabPane = (SysTabbedPane) tabPane;
			if (tabPane.isEnabled() && tabPane.isEnabledAt(tabIndex)) {
				g.setColor(tabPane.getForegroundAt(tabIndex));
				BasicGraphicsUtils.drawString(g, title,
						mtabPane.getMnemonicAt(tabIndex), textRect.x,
						textRect.y + metrics.getAscent());
			} else {
				g.setColor(tabPane.getBackgroundAt(tabIndex).brighter());
				BasicGraphicsUtils.drawString(g, title,
						mtabPane.getMnemonicAt(tabIndex), textRect.x,
						textRect.y + metrics.getAscent());
				g.setColor(tabPane.getBackgroundAt(tabIndex).darker());
				BasicGraphicsUtils.drawString(g, title,
						mtabPane.getMnemonicAt(tabIndex), textRect.x - 1,
						textRect.y + metrics.getAscent() - 1);
			}
		}
	}
}
